package org.base.admin.modules.base;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.base.admin.utils.web.WebSecurityUtils;
import org.base.common.R;
import org.base.common.ResponseCode;
import org.base.dao.common.Page;
import org.base.dao.modules.base.BaseDO;
import org.base.dao.modules.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

public abstract class BaseController<T extends BaseDO,S extends BaseService<T>> extends AbstractController {
	
	@Autowired
	protected S baseService;
	
	@PostMapping("/page")
	@PreAuthorize("hasMyAuthority('read')")
	public R page(@RequestBody Page<T> page) {
		return R.result(baseService.findPage(page));
	}
	
	@PostMapping("/list")
	@PreAuthorize("hasMyAuthority('read')")
	public R list(@RequestBody Map<String,Object> condition) {
		return R.result(baseService.findList(condition));
	}
	
	@GetMapping("/get/{id}")
	@PreAuthorize("hasMyAuthority('read')")
	public R info(@PathVariable("id") Long id) {
		return R.result(baseService.findById(id));
	}
	
	@PostMapping("/save")
	@PreAuthorize("hasMyAuthority('create')")
	public R save(@RequestBody T entity) {
		Long userId = WebSecurityUtils.getUserId();
		entity.setCreateBy(userId);
		entity.setUpdateBy(userId);
		Date now = new Date();
		entity.setCreateTime(now);
		entity.setUpdateTime(now);
		return baseService.save(entity)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
		
	}
	
	@PutMapping("/update")
	@PreAuthorize("hasMyAuthority('write')")
	public R update(@RequestBody T entity) {
		entity.setCreateBy(null);
		entity.setCreateTime(null);
		entity.setUpdateBy(WebSecurityUtils.getUserId());
		entity.setUpdateTime(new Date());
		return baseService.updateById(entity)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}
	
	@DeleteMapping("/remove/{id}")
	@PreAuthorize("hasMyAuthority('delete')")
	public R remove(@PathVariable("id") Long id) {
		return baseService.removeById(id)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}
	
	@DeleteMapping("/remove")
	@PreAuthorize("hasMyAuthority('delete')")
	public R removeList(@RequestBody List<Long> ids) {
		return baseService.removeByIds(ids)?
				R.ok():
				new R(ResponseCode.OPERATION_FAILURE);
	}

}
